﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Lookstone.Data
{
	public static class DataReaderExtensions
	{
		#region //****** IDataReader Extensions ******//
		public static bool HasField(this IDataReader reader, string fieldName)
		{
			for (int i = 0; i < reader.FieldCount; i++)
			{
				if (string.Compare(reader.GetName(i), fieldName, true) == 0)
					return true;
			}

			return false;
		}

		public static T GetField<T>(this IDataReader reader, int index)
		{
			object fieldData = reader[index];

			if (fieldData == DBNull.Value)
				return default(T);

			return (T)fieldData;
		}

		public static T? GetNullableField<T>(this IDataReader reader, int index) where T : struct
		{
			object fieldData = reader[index];

			if (fieldData == DBNull.Value)
				return new T?();

			return (T)fieldData;
		}

		public static T GetField<T>(this IDataReader reader, string fieldName)
		{
			object fieldData = reader[fieldName];

			if (fieldData == DBNull.Value)
				return default(T);

			return (T)fieldData;
		}

		public static T? GetNullableField<T>(this IDataReader reader, string fieldName) where T : struct
		{
			object fieldData = reader[fieldName];

			if (fieldData == DBNull.Value)
				return new T?();

			return (T)fieldData;
		}
		#endregion //****** IDataReader Extensions ******//

		#region //****** DataRow Extensions ******//
		public static bool HasField(this DataRow row, string fieldName)
		{
			return row.Table.Columns.Contains(fieldName);
		}

		public static T GetField<T>(this DataRow row, int index)
		{
			object fieldData = row[index];

			if (fieldData == DBNull.Value)
				return default(T);

			return (T)fieldData;
		}

		public static T? GetNullableField<T>(this DataRow row, int index) where T : struct
		{
			object fieldData = row[index];

			if (fieldData == DBNull.Value)
				return new T?();

			return (T)fieldData;
		}

		public static T GetField<T>(this DataRow row, string fieldName)
		{
			object fieldData = row[fieldName];

			if (fieldData == DBNull.Value)
				return default(T);

			return (T)fieldData;
		}

		public static T? GetNullableField<T>(this DataRow row, string fieldName) where T : struct
		{
			object fieldData = row[fieldName];

			if (fieldData == DBNull.Value)
				return new T?();

			return (T)fieldData;
		}
		#endregion //****** DataRow Extensions ******//
	}
}
